package com.htx.zqs.blesmartmask.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Address;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.htx.zqs.blesmartmask.BuildConfig;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.ui.dialog.SelectDialog;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.CameraUtil;
import com.htx.zqs.blesmartmask.utils.LocationUtil;
import com.htx.zqs.blesmartmask.utils.MySpUtils;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.picker.SinglePicker;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by zhao on 2018/6/19.
 */

public class OrderInfoActivity extends BaseActivity {

    @InjectView(R.id.iv_av_choose_picture)
    CircleImageView ivFgChoosePicture;
    @InjectView(R.id.tv_av_choose_picture)
    TextView        tvAvChoosePicture;
    @InjectView(R.id.tv_av_name)
    TextView        tvAvName;
    @InjectView(R.id.tv_av_age)
    TextView        tvAvAge;
    @InjectView(R.id.tv_av_sex)
    TextView        tvAvSex;
    @InjectView(R.id.tv_av_phone)
    TextView        tvAvPhone;
    @InjectView(R.id.btn_av_commit)
    Button          btnAvCommit;
    @InjectView(R.id.ib_back)
    ImageButton     ibBack;
    @InjectView(R.id.tv_title)
    TextView        tvTitle;
    @InjectView(R.id.ib_menu)
    TextView        ibMenu;
    @InjectView(R.id.ll_title)
    LinearLayout    mLlTitle;
    @InjectView(R.id.ll_av_name)
    LinearLayout    mLlAvName;
    @InjectView(R.id.ll_av_age)
    LinearLayout    mLlAvAge;
    @InjectView(R.id.ll_av_sex)
    LinearLayout    mLlAvSex;
    @InjectView(R.id.ll_av_phone)
    LinearLayout    mLlAvPhone;
    private String[] ages;
    private String[] sexs;
    private String   orderName;
    private String   orderPhone;
    private int agePosition = -1;
    private String orderAge;
    private String orderSex;

    private int sexPositon = -1;
    private boolean    isCommitInfo;
    private CameraUtil cameraUtil;
    private File       tempFile;
    private Bitmap     bitmap;
    private HashMap map = new HashMap();
    private String   mUniquePsuedoID;
    private Location bestLocation;
    private String   city;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_info);
        ButterKnife.inject(this);

        initView();
    }

    private void initView() {
        mUniquePsuedoID = LocationUtil.getUniquePsuedoID();
        cameraUtil = new CameraUtil();
     //   ibMenu.setVisibility(View.VISIBLE);
        tvTitle.setText(getResources().getString(R.string.order_title));
//        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tvTitle.getLayoutParams();
//        layoutParams.setMargins(120, 0, 0, 0);
        // tvTitle.setLayoutParams(layoutParams);
        tvTitle.setTextColor(Color.WHITE);
        ages = new String[100];
        for (int i = 0; i < 100; i++) {
            ages[i] = i + "";
        }
        sexs = new String[2];
        sexs[0] = getResources().getString(R.string.order_sex_man);
        sexs[1] = getResources().getString(R.string.order_sex_woman);

    }

    private void getUserAddress() {
        if (BlEUtile.isNetworkConnected(this)) {
            bestLocation = LocationUtil.getBestLocation(this);
            List<Address> locationInfos = LocationUtil.getLocationInfo(bestLocation, this);
            if (locationInfos == null || locationInfos.size() == 0) {
                city = "";
                Log.e("city","===1111===");
            } else {
                city = locationInfos.get(0).getAdminArea() + locationInfos.get(0).getLocality();
                Log.e("city","===2222===");
            }
        }
    }

    public void rename(String string, final int id) {
        // layout = (LinearLayout) getLayoutInflater().inflate(R.layout.myedit,
        // null);
        LayoutInflater factory = LayoutInflater.from(this);
        View textEntryView = factory.inflate(R.layout.myedit, null);
        // removeView();
        //内部局部类，只能访问方法的final类型的变量
        final EditText mname_edit = (EditText) textEntryView
                .findViewById(R.id.rename_edit);
        if (id == R.id.tv_av_phone) {
            mname_edit.setInputType(InputType.TYPE_CLASS_PHONE);
        }
        final TextView mname_text = textEntryView.findViewById(R.id.rename_message);
        mname_text.setText(string);
        // 不是用这个方法获取EditText的内容的
        // mname_edit.addTextChangedListener(mTextWatcher);

        // create a dialog
        new AlertDialog.Builder(this)
                //  .setIcon(R.drawable.icon)
                //  .setTitle(R.string.title_name)
                .setView(textEntryView)
                .setNegativeButton(getResources().getString(R.string.cancle),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // TODO Auto-generated method stub
                            }
                        })
                .setPositiveButton(getResources().getString(R.string.confirm),
                        new DialogInterface.OnClickListener() {

                            private String newName;

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // dialog.
                                // TODO Auto-generated method stub
                                // Log.v(TAG, "你点击了确定");
                                if (!mname_edit.getText().toString().equals("")) {
                                    newName = mname_edit.getText().toString();
                                }

                                switch (id) {
                                    case R.id.tv_av_name:
                                        orderName = newName;
                                        tvAvName.setText(newName);
                                        break;
                                    case R.id.tv_av_phone:
                                        orderPhone = newName;
                                        tvAvPhone.setText(newName);
                                        break;
                                }
                                // newName = mname_edit.getText().toString();

                                //Log.v(TAG, "$$$$$btn.setText(newName);");
                            }
                        }).show();
    }

    private void requestChoose(String[] items, String textName, final int id) {
        SinglePicker<String> picker = new SinglePicker<>(this, items);
        picker.setCanLoop(false);//不禁用循环
        picker.setTopBackgroundColor(0xFFEEEEEE);
        picker.setTopHeight(50);
        picker.setTopLineColor(0xFF33B5E5);
        picker.setTopLineHeight(1);
        picker.setTitleText(textName);
        picker.setTitleTextColor(0xFF33B5E5);
        picker.setTitleTextSize(13);
        picker.setCancelTextColor(0xFF33B5E5);
        picker.setCancelTextSize(13);
        picker.setSubmitTextColor(0xFF33B5E5);
        picker.setSubmitTextSize(13);
        picker.setSelectedTextColor(0xFF33C5E5);
        picker.setUnSelectedTextColor(0xFF999999);
        picker.setWheelModeEnable(false);
        LineConfig config = new LineConfig();
        config.setColor(Color.BLUE);//线颜色
        config.setAlpha(120);//线透明度

        // config.setRatio(1);//线比率
        //  config.setThick(30);
        picker.setLineConfig(config);
        picker.setItemWidth(200);
        picker.setBackgroundColor(0xFFE1E1E1);
        //picker.setSelectedItem(isChinese ? "处女座" : "Virgo");
        switch (id) {
            case R.id.tv_av_age:
                picker.setSelectedIndex(16);
                break;
            case R.id.tv_av_sex:
                picker.setSelectedIndex(0);
                break;
        }

        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                // showToast("index=" + index + ", item=" + item);
                //test.setText(item);

                switch (id) {
                    case R.id.tv_av_age:
                        agePosition = index;
                        orderAge = item;
                        tvAvAge.setText(item);
                        break;
                    case R.id.tv_av_sex:
                        sexPositon = index;
                        orderSex = item;
                        tvAvSex.setText(item);
                        break;
//                    case R.id.tv_fg_phone:
//                        tvFgPhone.setText(item);
//                        break;
                }
            }
        });
        picker.show();
    }


    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    @OnClick({R.id.iv_av_choose_picture, R.id.ib_menu, R.id.tv_av_choose_picture, R.id.ll_av_name, R.id.ll_av_age,
            R.id.ll_av_sex, R.id.ll_av_phone, R.id.btn_av_commit, R.id.ib_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_av_choose_picture:
            case R.id.tv_av_choose_picture:

                List<String> names = new ArrayList<>();
                names.add(getResources().getString(R.string.camera));
                names.add(getResources().getString(R.string.album));

                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0:
                                tempFile = cameraUtil.useCamera(OrderInfoActivity.this, 0);
                                break;
                            case 1:
                                //  cameraUtil.usePicture(OrderInfoActivity.this);
                                //单选
                                ImageSelector.builder()
                                        .useCamera(true) // 设置是否使用拍照
                                        .setSingle(true)  //设置是否单选
                                        .setViewImage(true) //是否点击放大图片查看,，默认为true
                                        .start(OrderInfoActivity.this, 550); // 打开相册
                                break;
                        }
                    }
                }, names);


                break;
            case R.id.ll_av_name:
                rename(getResources().getString(R.string.change_name), R.id.tv_av_name);
                break;
            case R.id.ll_av_age:
                requestChoose(ages, getResources().getString(R.string.change_age), R.id.tv_av_age);
                break;
            case R.id.ll_av_sex:
                requestChoose(sexs, getResources().getString(R.string.change_sex), R.id.tv_av_sex);
                break;
            case R.id.ll_av_phone:
                rename(getResources().getString(R.string.change_phone), R.id.tv_av_phone);
                break;
            case R.id.btn_av_commit:
//                int i = 1/0 ;
                saveOrderInfo();
                break;
            case R.id.ib_back:

                break;
            case R.id.ib_menu:
                startActivity(new Intent(this, MainActivity.class));
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
            case Contants.CAMERA_REQUEST_CODE:   //调用相机后返回
                if (resultCode == RESULT_OK) {
                    //用相机返回的照片去调用剪裁也需要对Uri进行处理
                    CameraUtil.flushPciture(this, tempFile.getAbsolutePath());
                    Uri contentUri;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        contentUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", tempFile);
                        // cropPhoto(contentUri);
                        Log.e("camera", "onActivityResult哪里: " + contentUri);
                        contentUri = Uri.fromFile(tempFile);
                        //    Glide.with(this).load(contentUri).into(mHeader_iv);
                    } else {
                        Log.e("camera", "onActivityResult: 这" + Uri.fromFile(tempFile));
                        contentUri = Uri.fromFile(tempFile);
                    }
                    showPhoto(contentUri);
                }
                break;
            case 550:    //调用相册后返回
                if (resultCode == RESULT_OK) {
                    if (intent != null) {
                        //获取选择器返回的数据
                        ArrayList<String> images = intent.getStringArrayListExtra(
                                ImageSelectorUtils.SELECT_RESULT);
                        Log.e("=====361", "====" + images.get(0));
                        showPhoto(Uri.parse(images.get(0)));
                    }
                }
                break;
        }
    }

    private void showPhoto(Uri contentUri) {

        String path = contentUri.getPath();
        CameraUtil.flushPciture(this, path);
        SPUtil.put(this, "uri", path, "uri");
        Glide.with(this).load(new File(path)).into(ivFgChoosePicture);
        Log.e("camera", "onActivityResult: 这" + contentUri);
    }

    private void saveOrderInfo() {
        if (orderName == null || orderName.equals("")) {
            Toast.makeText(this, getResources().getString(R.string.input_name), Toast.LENGTH_SHORT).show();
        } else if (orderAge == null || orderAge.equals("")) {
            Toast.makeText(this, getResources().getString(R.string.input_age), Toast.LENGTH_SHORT).show();
        } else if (orderSex == null || orderSex.equals("")) {
            Toast.makeText(this, getResources().getString(R.string.input_sex), Toast.LENGTH_SHORT).show();
        } else if (orderPhone == null || orderPhone.equals("")) {
            Toast.makeText(this, getResources().getString(R.string.input_phone), Toast.LENGTH_SHORT).show();
        } else {
            if (BlEUtile.isNetworkConnected(this)) {
                getUserAddress();
                OkhttpUtils okhttpUtils = new OkhttpUtils(this, Contants.ORDER_INFO_CODE, new OkListener() {
                    @Override
                    public void onSuccess(int requestCode, String string) {
                        Log.e("====info===", "===397==" + string);
                    }

                    @Override
                    public void onError(int requestCode, IOException e) {
                        Log.e("====info===", "===402==" + e);
                    }
                });
                map.clear();
                map.put("usernick", orderName);
                map.put("age", orderAge);
                map.put("sex", orderSex);
                map.put("phone", orderPhone);
                map.put("uuid", mUniquePsuedoID);
                map.put("userge", city);
                Log.e("====info===", "===412==" + map.toString());
                okhttpUtils.postForm(Contants.ORDER_INFO_CODE, Contants.BASE_URL + "ug.link", map);
            }

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("orderName", orderName);
                jsonObject.put("orderAge", orderAge);
                jsonObject.put("orderSex", orderSex);
                jsonObject.put("orderPhone", orderPhone);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            isCommitInfo = true;
            MySpUtils.putString(MySpUtils.KEY_USER_NAME,orderName);
            SPUtil.put(this, "orderInfo", jsonObject, "orderInfo");
            Log.e("json", "saveOrderInfo: " + jsonObject);
            SPUtil.put(this, "isCommitInfo", isCommitInfo, "isCommitInfo");
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

}
